//
//  NewFeatureViewController.swift
//  HMWeibo08
//
//  Created by 唐万超 on 15/7/31.
//  Copyright © 2015年 唐万超. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class NewFeatureViewController: UICollectionViewController {
    
    private let layout = HMFlowLayout()
    
    init() {
    
        super.init(collectionViewLayout: layout)
        
    }

    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        
        super.init(coder: aDecoder)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(NewFeatureViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

   

    // MARK: UICollectionViewDataSource
    
    // 设置item个数
    private let imageCount = 4
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return imageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureViewCell
    
        cell.imageIndex = indexPath.item
    
        return cell
    }

    // 去掉状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    /// 显示完成cell － indexpath 是之前消失 cell 的 indexPath
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
//        print(indexPath)
        // 得到当前的图片索引
        let index = collectionView.indexPathsForVisibleItems().last!
        print(index)
        
        print(index.item)
        
        // 当显示最后一页  index.item
        if index.item == imageCount - 1 {
        
            // 获取当前的cell
            let cell = collectionView.cellForItemAtIndexPath(index) as! NewFeatureViewCell
            cell.startAnim()
            
        }
        
    }

}

class NewFeatureViewCell: UICollectionViewCell {
    
    // 定义图片的索引 ，私有属性
    private var imageIndex:Int = 0 {
        didSet {
        
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            
            // 此处设置完cell的图片就把按钮隐藏
            startButton.hidden  = true
        }
    
    }
    
    // 按钮点击方法
    func startBtnClick() {
        
        // 点击开始体验 进行页面跳转，发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(HMRootViewSwitchNotification, object: true)
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        
        setUI()
        
    }
    
    // 开启按钮动画
    private func startAnim() {
        
        // 当开启动画显示按钮
        startButton.hidden = false
        
        startButton.userInteractionEnabled = false
    
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
                self.startButton.userInteractionEnabled = true
        }
        
    }
    
    // 设置UI
    func setUI() {
    
        contentView.addSubview(iconView)
        contentView.addSubview(startButton)
        
        // 设置约束
        iconView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview":iconView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview":iconView]))
        
        
        // 设置按钮的约束
        startButton.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
    
    }
    
    // 懒加载子控件
    private lazy var iconView = UIImageView()
    
    // 懒加载按钮
    private lazy var startButton: UIButton = {
    
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("开始体验", forState: UIControlState.Normal)
        
        // 会根据背景图片的大小自动设置按钮的大小
        button.sizeToFit()
        
        // 默认设置按钮隐藏   // 提示: 按钮的隐藏属性会因为复用工作不正常，删不删除都行
      //  button.hidden = true
        
        // 按钮点击
        button.addTarget(self, action: "startBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        
    }()
}

/// 自定义流水布局
private class HMFlowLayout: UICollectionViewFlowLayout {

    // 当没有设置layout，获取数量之后，准备cell之前，会调用一次来准备布局属性
    private override func prepareLayout() {
        
        itemSize = collectionView!.bounds.size
        
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        
    }
    
}
